<?php

set_time_limit(0);

/**
 * Ctdocumento form
 * @subpackage form
 * @author     Ivan
 */
class CtdocumentoForm extends BaseCtdocumentoForm
{

  public function configure()
  {
    unset($this['ct_documento_caracteristica_list'], $this['fechaCambio'], $this['idDocumentoPadre'], $this['usuario'], $this['fechaAlta'], $this['fechaBaja'], $this['fotoPath']);

    $sf_formatter_revisited = new documentoFormatter($this->getWidgetSchema());
    $this->getWidgetSchema()->addFormFormatter("documento", $sf_formatter_revisited);
    $this->getWidgetSchema()->setFormFormatterName("documento");
    if (!($this->getOptions('new_for_add_repetible', false))) {
      foreach ($this->padres as $key => $padre)
      {
        $form_repeticiones = new sfForm();
        $form_repeticiones->getWidgetSchema()->addFormFormatter("documento", $sf_formatter_revisited);
        $form_repeticiones->getWidgetSchema()->setFormFormatterName("documento");
        if ($padre->isRepetible()){
          $repeticiones = $padre->getArrayRepeticiones($this->getObject());
          $show_delete = (count($repeticiones) > 1);
          foreach($repeticiones as $repeticion)
          {
            $form_repeticiones->embedForm('r' . $repeticion['IDITERACION'], new CtCaracteristicaPadreForm($padre,array('documento'=>$this->getObject(), 'show_delete' => $show_delete,'next_child' => $repeticion['IDITERACION'])));
          }
          $this->embedForm('padre'.($key+1),$form_repeticiones);
        }
        else{
          $form_repeticiones->embedForm('nr' . 1, new CtCaracteristicaPadreForm($padre,array('documento'=>$this->getObject())));
          $this->embedForm('padre'.($key+1), $form_repeticiones);
        }
      }
    }
    ##Esto no lo hace el ALLOW_EXTRAS ni el CSRF....
    $this->validatorSchema->setOption('allow_extra_fields', true);
    $this->widgetSchema->setNameFormat('documento_monografico[%s]');
    $this->disableLocalCSRFProtection();
  }

  public function doSave($con = null)
  {
    $documento = $this->getObject();
    $documento->setFechacambio(time());
    $documento->setUsuario(sfContext::getInstance()->getUser()->getGuardUser()->getId());
    if ($this->isNew())
    {
      $documento->setFechaalta(time());
    }

    foreach ($this->values as $key => $padre)
    {
      if (strpos($key,'padre') !== false){
        foreach($padre as $iteracion => $r){
          if (strpos($iteracion,'nr') === false){
              if ($r['c1']['valorCaracteristica'] == '-1') {
                  if ($r['c1']['id'] != ''){
                      unset($r['idCaracteristicaPadre']);
                      $ids = array();
                      foreach($r as $caracteristica) {
                          $ids[] = $caracteristica['id'];
                      }
                      $documento_caracteristicas = CtDocumentoCaracteristicaPeer::retrieveByPKs($ids);
                      foreach($documento_caracteristicas as $documento_caracteristica) {
                          $documento_caracteristica->delete($con);
                      }
                  }
                  unset($this->taintedValues[$key][$iteracion]);
                  unset($this->values[$key][$iteracion]);
                  unset($this->embeddedForms[$key][$iteracion]);
              }
          }
        }
      }
    }

    parent::doSave($con);
  }

  public function bind(array $taintedValues = null, array $taintedFiles = null)
  {
    foreach ($taintedValues as $key => $padre)
    {
      if (strpos($key,'padre') !== false){
        foreach($padre as $iteracion => $r){
          if (strpos($iteracion,'nr') === false){
              $id_caracteristica_padre = $r['idCaracteristicaPadre'];
              unset($r['idCaracteristicaPadre']);
              $caracteristica = $r['c1'];
              if (($caracteristica['id'] == '') && ($r['todelete'] == 0)) {
                $this->insertRepetibleToBind($id_caracteristica_padre, $key, $iteracion, $caracteristica['idIteracion']);
              }
              
              if ($r['todelete'] == 1){
                  $taintedValues[$key][$iteracion]['c1']['valorCaracteristica'] = '-1';
              }
          }
        }
      }
    }
    parent::bind($taintedValues, $taintedFiles);
  }

  function insertRepetibleToBind($id_caracteristica_padre, $padre,$iteracion, $next_repetible){
    $padre_form = $this->embeddedForms[$padre];
    $padre_peer = CtCaracteristicaPadrePeer::retrieveOneByIdPadre($id_caracteristica_padre);
    if (!(array_key_exists($iteracion, $padre_form->embeddedForms))){
        $padre_form->embedForm($iteracion, new CtCaracteristicaPadreForm($padre_peer,array('documento'=>$this->getObject(), 'show_delete' => true,'next_child' => $next_repetible)));
        $this->embedForm($padre,$padre_form);
    }
  }
  
  function addRepetible($id_caracteristica_padre, $padre, $iteracion, $next_repetible){
    $padre_peer = CtCaracteristicaPadrePeer::retrieveOneByIdPadre($id_caracteristica_padre);
    $form_repeticiones = new sfForm();
    $sf_formatter_revisited = new documentoFormatter($this->getWidgetSchema());
    $form_repeticiones->getWidgetSchema()->addFormFormatter("documento", $sf_formatter_revisited);
    $form_repeticiones->getWidgetSchema()->setFormFormatterName("documento");
    $form_repeticiones->embedForm($iteracion, new CtCaracteristicaPadreForm($padre_peer,array('documento'=>$this->getObject(), 'show_delete' => true,'next_child' => $next_repetible)));
    $this->embedForm($padre,$form_repeticiones);
  }
}

